package com.liu.learning.manual_paper.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czy.learning.questionnature.service.QuestionNatureService;
import com.lin.learning.questionmanagement.service.QuestionService;
import com.liu.learning.manual_paper.dto.PaperQuestionsDTO;
import com.liu.learning.manual_paper.mapper.ManualPaperMapper;
import com.liu.learning.manual_paper.service.SelectQuestionService;
import com.liu.learning.manual_paper.vo.AnswerVO;
import com.liu.learning.manual_paper.vo.QuestionVO;
import com.our.learning.infrastructure.constant.ResponseStatusEnum;
import com.our.learning.infrastructure.po.Paper;
import com.our.learning.infrastructure.po.Question;
import com.our.learning.infrastructure.po.QuestionNature;
import com.our.learning.infrastructure.pojo.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SelectQuestionServiceImpl extends ServiceImpl<ManualPaperMapper, Paper> implements SelectQuestionService {

    @Autowired
    private final ManualPaperMapper paperMapper;
    @Autowired
    private final QuestionService questionService;
    @Autowired
    private final QuestionNatureService questionNatureService;

    public SelectQuestionServiceImpl(ManualPaperMapper paperMapper, QuestionService questionService, QuestionNatureService questionNatureService) {
        this.paperMapper = paperMapper;
        this.questionService = questionService;
        this.questionNatureService = questionNatureService;
    }

//    @Override
//    public Response createPaper(String name) {
//        // 新建试卷
//        Paper paper = new Paper();
//        paper.setName(name);
//        if (save(paper) != true) {
//            return new Response(ResponseStatusEnum.DATABASE_ERROR);
//        }
//        QueryWrapper<Paper> queryWrapper = new QueryWrapper<>();
//        queryWrapper.orderByDesc("create_time").last("LIMIT 1");
//        paper = paperMapper.selectOne(queryWrapper);
//        return new Response(ResponseStatusEnum.OK)
//                .addData("paper", paper);
//    }

    @Override
    public Paper createPaper(Paper paper) {
        // 新建试卷
        paper.setType(1);
        if (!save(paper)) {
            return null;
        }
        QueryWrapper<Paper> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time").last("LIMIT 1");
        paper = paperMapper.selectOne(queryWrapper);
        return paper;
    }

    //    @Override
//    public Response addQuestionToPaper(PaperQuestionsDTO paperQuestionsDTO) {
//        Integer paperId = paperQuestionsDTO.getPaperId();
//        List<Integer> questionsId = paperQuestionsDTO.getQuestionsId();
//        // 获取试卷信息
//        Paper paper = paperMapper.selectById(paperId);
//        if (paper == null) {
//            // 试卷不存在
//            return new Response(ResponseStatusEnum.BAD_REQUEST)
//                    .setMsg("试卷不存在");
//        }
//        // 根据题目ID列表从题库子系统获取题目列表
//        List<Question> questions = questionService.getQuestionByIdsLocal(questionsId);
//        if (questions.isEmpty()) {
//            // 题目列表为空，不执行添加操作
//            return new Response(ResponseStatusEnum.BAD_REQUEST)
//                    .setMsg("题目列表为空");
//        }
//        // 将题目添加到试卷中
//        paper.setQuestions(questions);
//        // 更新联表信息
//        int i = 1;
//        for(Question question : questions) {
//            QuestionPO paperQuestion = new QuestionPO();
//            paperQuestion.setPaperId(paperId);
//            paperQuestion.setQuestionId(question.getId());
//            paperQuestion.setTitleNo(i++);
//            if (paperQuestionService.save(paperQuestion) != true) {
//                return new Response(ResponseStatusEnum.DATABASE_ERROR);
//            }
//        }
//        return new Response(ResponseStatusEnum.OK).addData("paper",paper);
//    }
    @Override
    public Response addQuestionToPaper(PaperQuestionsDTO paperQuestionsDTO) {
        String paperName = paperQuestionsDTO.getPaperName();
        if(paperName == null) return new Response(ResponseStatusEnum.BAD_REQUEST).setMsg("试卷名字为空");
        Paper paper = new Paper();
        paper.setName(paperName);
        String[] s = paperQuestionsDTO.getIds().split(",");
        List<String> l = Arrays.asList(s);
        List<String> nl = new ArrayList<>(l);
        List<Integer> questionsId = nl.stream().map(Integer::parseInt).collect(Collectors.toList());
        // 根据题目ID列表从题库子系统获取题目列表
        List<Question> questions = questionService.getQuestionByIdsLocal(questionsId);
        if (questions.isEmpty()) {
            // 题目列表为空，不执行添加操作
            return new Response(ResponseStatusEnum.BAD_REQUEST)
                    .setMsg("题目列表为空");
        }
        // 将题目和答案添加到试卷中
        List<QuestionVO> questionVOS = new ArrayList<>();
        List<AnswerVO> answerVOS = new ArrayList<>();
        int i = 1;
        int num = 0;
        List<String> type= new ArrayList<>(Arrays.asList("select", "blank", "picture"));
        while (num<3) {
            int j = questions.size();
            int k = 0;
            while (k < j) {
                Question question = questions.get(k++);
                if (question.getType().equals(type.get(num))) {
                    QuestionVO questionVO = new QuestionVO(question.getId(),i, question.getContent(), type.get(num), null);
                    questionVOS.add(questionVO);
                    QuestionNature questionNature = questionNatureService.getQuestionNatureByIdLocal(question.getId());
                    if(questionNature == null) return new Response(ResponseStatusEnum.BAD_REQUEST).setMsg("ID:"+question.getId()+" "+"题目性质不存在");
                    AnswerVO answerVO = new AnswerVO(i++,questionNature.getAnswer());
                    answerVOS.add(answerVO);
                    questions.remove(question);
                    j--;
                    k--;
                }
            }
            if(j==0) break;
            num++;
        }
        String qj = JSON.toJSONString(questionVOS);
        String aj = JSON.toJSONString(answerVOS);
        paper.setQuestions(qj);
        paper.setAnswers(aj);
        paper.setQuestionNum(i - 1);
        paper = createPaper(paper);
        if (paper == null) return new Response(ResponseStatusEnum.DATABASE_ERROR).setMsg("创建试卷失败");
        else return new Response(ResponseStatusEnum.OK).setMsg("创建试卷成功");
    }
}
